﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using popLib;
using PhotoMgr.src.common;
using System.Windows.Forms;
using System.Data;

namespace PhotoMgr.src.database
{
    public partial class DBManager
    {
        public static ReturnSet Search_User(int page, int itemPerPage, Hashtable searchData)
        {
            var entity = new PhotoMgrEntities(GenConnectionString());
            //var entity = new PhotoMgrEntities(GenConnectionString());
            entity.CommandTimeout = 180;

            IQueryable<User> result = entity.Users.OrderBy(x => x.Username);

            if (searchData.ContainsKey("Username"))
            {
                string Username = searchData["Username"].ToString();
                result = result.Where(x => x.Username.Contains(Username));
            }

            if (searchData.ContainsKey("Fullname"))
            {
                string Fullname = searchData["Fullname"].ToString();
                result = result.Where(x => x.Fullname.Contains(Fullname));
            }

            if (searchData.ContainsKey("RoleCode"))
            {
                int RoleCode = NumberLib.getInt(searchData["RoleCode"]);
                result = result.Where(x => x.RoleCode == RoleCode);
            }

            if (searchData.ContainsKey("Status"))
            {
                string Status = searchData["Status"].ToString();
                result = result.Where(x => x.Status == Status);
            }

            var pageData = new PageData();

            if (result.Count() > 0)
            {
                //total pages
                pageData.TotalPages = result.Count() / itemPerPage;
                if (result.Count() % itemPerPage > 0)
                {
                    pageData.TotalPages++;
                }

                //current page
                pageData.CurrentPage = page;
                if (page > pageData.TotalPages)
                {
                    pageData.CurrentPage = pageData.TotalPages;
                }

                //total records
                pageData.TotalRecords = result.Count();

                //get filter record in page
                result = result.Skip((pageData.CurrentPage - 1) * itemPerPage);
                result = result.Take(itemPerPage);
                pageData.DataSource = result.ToList();
            }
            else
            {
                pageData = new PageData(1, 1, result.ToList(), 0);
            }

            return new ReturnSet(true, pageData);
            //return ProcessPageData(page, result, itemPerPage);            
        }

        public static ReturnSet Search_Contest(int page, int itemPerPage, Hashtable searchData)
        {
            var entity = new PhotoMgrEntities(GenConnectionString());

            IQueryable<Contest> result = entity.Contests.OrderBy(x => x.ContestID);

            if (searchData.ContainsKey("Username"))
            {
                string Username = searchData["Username"].ToString();
                result = result.Where(x => x.ContestName.Contains(Username));
            }

            if (searchData.ContainsKey("Fullname"))
            {
                string Fullname = searchData["Fullname"].ToString();
                result = result.Where(x => x.ContestName.Contains(Fullname));
            }

            return ProcessPageData(page, result, itemPerPage);
        }

        public static String GetUsername(int user_id)
        {
            String username = "";
            var entity = new PhotoMgrEntities(GenConnectionString());

            IQueryable<User> result = entity.Users.Where(x => x.UserID == user_id);

            if (result.Count() < 1)
            {
                return "Nouser";
            }

            if (result.Count() == 1)
            {
                username = result.First().Username;
            }
            else
            {
                MessageBox.Show("Có nhiều người trùng username", "Thông báo");
                username = result.First().Username;
            }

            return username;
        }

        public static int GetIDFromName(String username)
        {
            var entity = new PhotoMgrEntities(GenConnectionString());

            int resultX = 0;

            IQueryable<User> result = entity.Users.Where(x => x.Username == username);

            if (result.Count() < 1)
            {
                return 4;
            }

            if (result.Count() == 1)
            {
                resultX = result.First().UserID;
            }
            else
            {
                MessageBox.Show("Có nhiều người trùng ID", "Thông báo");
                resultX = result.First().UserID;
            }

            return resultX;
        }

        public static string User_GetNameFromID(int id)
        {
            //var entity = new PhotoMgrEntities(GenConnectionString());

            //int resultX = 0;

            //IQueryable<User> result = entity.Users.Where(x => x.UserID == id);

            //if (result.Count() > 0)
            //{

            //}

            return "";
        }

        public static database.User Detail_User(int user_id)
        {
            database.User username;
            var entity = new PhotoMgrEntities(GenConnectionString());

            IQueryable<User> result = entity.Users.Where(x => x.UserID == user_id);

            if (result.Count() < 1)
            {
                return null;
            }

            if (result.Count() == 1)
            {
                username = result.First();
            }
            else
            {
                MessageBox.Show("Có nhiều người trùng username", "Thông báo");
                username = result.First();
            }

            return username;
        }

        public static ReturnSet CheckExistedUsername(string usernamerStr)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                String usernameX = Global.GetString(usernamerStr);

                var rs = entity.Users.Where(x => x.Username == usernameX);

                if (rs.Count() > 0)
                {
                    database.User item = rs.First();
                    return new ReturnSet(true, item.Username);
                }

                return new ReturnSet(false);
            }
        }

        public static ReturnSet Save_User(bool isUpdateMode, database.User updatedItem, database.User originalItem)
        {
            using (var entity = new PhotoMgrEntities(GenConnectionString()))
            {
                try
                {
                    //save Bao Cao BHXH first============================================
                    entity.Users.Attach(updatedItem);

                    if (isUpdateMode)
                    {
                        entity.ApplyOriginalValues("Users", originalItem);
                    }
                    else
                    {
                        entity.ObjectStateManager.ChangeObjectState(updatedItem, EntityState.Added);
                    }

                    entity.SaveChanges();

                    return new ReturnSet(true, updatedItem);
                }
                catch (OptimisticConcurrencyException ocex)
                {
                    entity.Users.Detach(updatedItem);
                    Global.WriteLog(ocex, "Save_HanhChanh_LuongCanBans.OptimisticConcurrencyException");
                    return new ReturnSet(false, Global.DBErrorType.RecordOutOfDate, ocex.Message);
                }
                catch (UpdateException uex)
                {
                    entity.Users.Detach(updatedItem);
                    Global.WriteLog(uex, "Save_HanhChanh_LuongCanBans.UpdateException");
                    Global.WriteLog(uex.InnerException, "Save_KeToan_ChiPhiCongNoNoiTru.UpdateException.InnerException");
                    return new ReturnSet(false, Global.DBErrorType.AddExistedRecord, uex.Message);
                }
                catch (Exception ex)
                {
                    entity.Users.Detach(updatedItem);
                    Global.WriteLog(ex, "Save_HanhChanh_LuongCanBans.Exception");
                    Global.WriteLog(ex.InnerException, "Save_KeToan_ChiPhiCongNoNoiTru.Exception.InnerException");
                    return new ReturnSet(false, Global.DBErrorType.UnknownError, ex.Message);
                }
            }
        }
    }
}
